<template>
  <!-- Default box -->
  <div class="card">
    <el-backtop></el-backtop>
    <div class="card-header">
      <h3 class="card-title">{{ paperTitle }}</h3>
      <span v-show="isSubmit" style="margin-left: 900px">剩余时间:{{ endTime }}</span>
    </div>
    <div class="card-body">
      <el-form ref="form" :model="form" label-width="80px" v-show="!isSubmit" :rules="rules">
        <el-form-item label="学科" prop="subjectId">
          <el-select v-model="form.subjectId" placeholder="请选择学科" @change="chooseSubject">
            <el-option v-for="item in subjectList" :key="item.id" :label="item.sname" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阶段" prop="stageId">
          <el-select v-model="form.stageId" placeholder="请选择阶段" :disabled="isDisable">
            <el-option v-for="item in stageList" :key="item.id" :label="item.stname" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="autoGeneratePaper('form')">生成试卷</el-button>
        </el-form-item>
      </el-form>

      <form @submit.prevent="carryPaper()" v-show="isSubmit">
        <div>
          <div v-for="(item, index) in answerForm.questions" :key="index" style="margin-top: 10px">
            <p>({{ index + 1 }})&nbsp;&nbsp;&nbsp;&nbsp;{{ item.stem }}</p>
            <el-radio-group v-model="item.answer">
              <el-radio :label="item.optionA" value="item.optionA"></el-radio>
              <el-radio :label="item.optionB" value="item.optionB"></el-radio>
              <el-radio :label="item.optionC" value="item.optionC"></el-radio>
              <el-radio :label="item.optionD" value="item.optionD"></el-radio>
              <el-radio :label="item.optionE" value="item.optionE" v-show="item.optionE"></el-radio>
            </el-radio-group>
            <hr />
          </div>
          <button type="primary" class="btn btn-secondary" :disabled="isTimeOut">
            提交
          </button>
        </div>
      </form>
    </div>
  </div>
  <!-- /.card-body -->
</template>
<script>
export default {
  name: "PaperMain",
  data() {
    return {
      paperTitle: "自动生成试卷",
      form: {
        subjectId: "",
        stageId: "",
      },
      answerForm: {
        questions: [],
        userId: 0,
      },
      isDisable: true,
      subjectList: [],
      stageList: [],
      isSubmit: false,
      rules: {
        subjectId: [
          { required: true, message: "请选择学科", trigger: "change" },
        ],
        stageId: [{ required: true, message: "请选择阶段", trigger: "change" }],
      },
      examTime: 1000 * 60 * 60,
      endTime: 0,
      isTimeOut: false,
      myInterval: {},
      userInfo: {},
    };
  },
  methods: {
    getSubjectList() {
      this.axiosJSON.post("/subject/getAllWithoutPage").then((result) => {
        this.subjectList = result.data.data;
      });
    },
    chooseSubject() {
      this.isDisable = false;
      this.axiosJSON
        .get("/stage/getAllWithSubjectID?subjectId=" + this.form.subjectId)
        .then((result) => {
          this.stageList = result.data.data;
        });
    },
    autoGeneratePaper(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          this.isSubmit = true;
          this.axiosJSON
            .get(
              "/paper/autoGenerate?sid=" +
              this.form.subjectId +
              "&stid=" +
              this.form.stageId +
              "&userid=" +
              this.userInfo.id
            )
            .then((result) => {
              console.log(result.data.data);
              this.answerForm.questions = result.data.data;
            });
          this.setEndTime();
          this.paperTitle = "开始答题";
        }
      })
    },
    // 主动提交试卷
    carryPaper() {
      this.$confirm("是否提交试卷？（无法撤销）", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.submitPaper();
          this.isTimeOut = true;
          clearInterval(this.myInterval);
          this.examTime = "已提交试卷";
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 发起提交试卷请求
    submitPaper() {
      console.log(this.answerForm.questions);
      let answer = "";
      // 将答案转换为选项
      for (let i = 0; i < this.answerForm.questions.length; i++) {
        if (this.answerForm.questions[i].answer == "") answer = "";
        else
          switch (this.answerForm.questions[i].answer) {
            case this.answerForm.questions[i].optionA:
              answer += "a";
              break;
            case this.answerForm.questions[i].optionB:
              answer += "b";
              break;
            case this.answerForm.questions[i].optionC:
              answer += "c";
              break;
            case this.answerForm.questions[i].optionD:
              answer += "d";
              break;
            case this.answerForm.questions[i].optionE:
              answer += "e";
              break;
          }

        this.answerForm.questions[i].answer = answer;
        answer = "";
      }

      this.axiosJSON
        .post("/paper/submitPaper", this.answerForm)
        .then((result) => {
          this.$message({ type: "success", message: "提交成功" });
        });
    },
    // 生成试卷后，设置倒计时
    setEndTime() {
      this.myInterval = setInterval(() => {
        this.examTime -= 1000;
        this.isExamTimeOut();
        this.formatMsToDate();
      }, 1000);
    },
    // 判断考试时间是否结束，并执行考试结束处理
    isExamTimeOut() {
      if (this.examTime <= 0) {
        clearInterval(this.myInterval);
        this.endTime = "考试时间结束";
        this.isTimeOut = true;
        this.submitPaper();
      }
    },
    // 格式化时间
    formatMsToDate() {
      if (this.examTime) {
        let oDate = new Date(this.examTime);
        // let oHour = oDate.getHours();
        let oMin = oDate.getMinutes();
        let oSen = oDate.getSeconds();
        this.endTime =
          "00" + ":" + this.addZero(oMin) + ":" + this.addZero(oSen);
      }
    },
    //该方法用于给日期、时间补零
    addZero(num) {
      if (parseInt(num) < 10) {
        num = "0" + num;
      }
      return num;
    },
  },
  mounted() {
    this.getSubjectList(),
      (this.userInfo = this.$store.getters.getLoginUser),
      (this.answerForm.userId = this.userInfo.id);
  },
};
</script>

<style>
</style>
